
//
// 120626 - (AH) - (Huset) Created, just the idea, decided to wait with
//                 implementation.
// 120813 - (AH) - Completed implementation.
//

package org.soekrat.server.servlets.json;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.japril.servlet.HttpRequestDef;
import org.soekrat.server.serialization.json.JsonToHttpRequest;
import org.soekrat.server.serialization.json.JsonToHttpRequest.ParseResult;
import org.soekrat.server.servlets.AbstractSoekratHttpServlet;

/**
 * <p>
 *   Implements generic request for a request given in Json code. 
 * </p>
 * @author Arne Halvorsen (AH)
 * @author Laetitia Le Chatton (LLC)
 */
@SuppressWarnings("serial")
public final class JsonHttpServlet extends AbstractSoekratHttpServlet 
{
  /**
   * <p>
   *   Constructor.
   * </p>
   */
  public JsonHttpServlet(){}
  
  @Override
  protected void handleRequest(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException 
  {
    HttpRequestDef def=getHttpRequestDef();  
  
    if (!hasParameters(req))
    {
      PrintWriter pw=printSimpleHtmlStart(res);
      pw.println(def.compileApiHtml());
      printSimpleHtmlEnd(pw);
    }
    else
    {     
      if (!validate(res, def, req)) return;
      
      
      
      String json=def.fetch(JSON_REQ.name(), req).getStringValue();
      
      String reqUrl=req.getRequestURL().toString();
      String stem=getReqUrlStem(reqUrl);
      
      System.out.println("req-url-stem: "+stem);
      
      JsonToHttpRequest jthr=new JsonToHttpRequest(stem);
      ParseResult pr=jthr.toRequestUrl(json);
      if (pr.ok)
      {
        String urls=pr.res;
        
        URL url=new URL(urls);
        HttpURLConnection con=(HttpURLConnection)url.openConnection();
        con.setDoOutput(true);
        con.setInstanceFollowRedirects(false);
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "text/plain");
        con.setRequestProperty("charset", "utf-8");
        con.connect();
        
        InputStream is=con.getInputStream();
        
        res.setContentType("application/json");
        PrintWriter pw=res.getWriter();
        
        printStream(is, pw);
      }
      else
      {
        respond(res, pr.res);
      }
    }
  }

  @Override
  public HttpRequestDef getHttpRequestDef() 
  {
    return new HttpRequestDef("/soekrat_server/json_req")
    .desc("Json Request").parameter(JSON_REQ);
  }
  
  private static void printStream(InputStream is, PrintWriter pw) 
    throws IOException
  {
    BufferedReader br=new BufferedReader(new InputStreamReader(is));
    String line=br.readLine();
    while (line!=null)
    {
      pw.println(line);
      line=br.readLine();
    }
  }
  
  private String getReqUrlStem(String url)
  {
    int idx=url.lastIndexOf('/');
    if (idx==-1) return null;
    return url.substring(0, idx);
  }
  
}
